<template>
  <div>
    <!-- 热门标签 -->
    <div>
      <label>热门标签：</label>
      <el-tag
        v-for="(tag, index) in hotTags"
        :key="index"
        :type="tagColor[index]"
        class="ms-3"
        @click="selHotTag(tag.tagName)"
      >
        {{ tag.tagName }}
      </el-tag>
    </div>
    <!-- 选中标签 -->
    <div>
      <label>选中标签：</label>
      <el-tag
        class="ms-3"
        v-for="(tag, index) in selectTags"
        :key="index"
        :type="tagColor[index]"
        closable
        @close="delSelctTags(index)"
        >{{ tag }}</el-tag
      >
      <el-input
        class="ms-3"
        v-model="newTags"
        style="width: 5rem"
        size="small"
        @keyup.enter="addNewTag"
      ></el-input>
    </div>
  </div>
</template>

<script>
export default {
  name: "NoteTag",
  emits: ["getTags"], //emits数组用于自定义事件，定义getTags事件，用于传递数组给父组件
  props:{
    detailTags:Array,
  },
  data() {
    return {
      hotTags: [
        { tagName: "前端" },
        { tagName: "js" },
        { tagName: "CSS" },
        { tagName: "VUE" },
        { tagName: "Bootstrap" },
      ],
      tagColor: ["", "success", "info", "warning", "danger"],
      selectTags: [],
      newTags: null,
    };
  },
  methods: {
    //热门标签点击事件
    selHotTag(tagName) {
      this.selectTags.push(tagName);
    },
    //删除选中标签
    delSelctTags(index) {
      this.selectTags.splice(index, 1);
    },
    addNewTag() {
      this.selectTags.push(this.newTags);
      this.newTags = null;
    },
  },
  watch: {
    selectTags: {
      //当selectTags数据通过调用自定义事件getTags,都会触发handler()函数
      handler() {
        this.$emit("getTags", this.selectTags);
      },
      deep: true,
    },
    detailTags: {
      handler() {
        if (this.detailTags != undefined) {
          //使用foreach循环，遍历detailtags中的元素
          this.detailTags.forEach((tag) => {
            this.selectTags.push(tag.tagName);
          });
        }
      },
      //deep: true,
    },
    deep: true,
  },
};
</script>

<style>
</style>
